import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/king/king_logic.dart';
import 'package:sports_new/entity/king/king_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/king/items/king_scroll_bar.dart';
import 'package:sports_new/view/pick/items/banner_scaffold.dart';
import 'package:sports_new/view/pick/items/rect_date_bar.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/share/share_button.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../resources/styles.dart';
import '../../utils/routes.dart';
import '../../utils/user.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/base/qkd_dialog.dart';
import 'items/king_rule_item.dart';

class KingPage extends StatefulWidget {
  const KingPage({super.key});

  @override
  State<KingPage> createState() => _KingPageState();
}

class _KingPageState extends State<KingPage> {
  final KingLogic logic = Get.put(KingLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<KingLogic>(builder: (logic) {
      return VisibilityDetector(
        key: const Key("king"),
        onVisibilityChanged: (VisibilityInfo info) {
          if (User.info != null && logic.data != null) logic.getData();
        },
        child: BannerScaffold(
            type: "king",
            titleFade: true,
            needScroll: true,
            title: "预测King",
            bannerHeight: Get.width*242/375,
            action: const [
              ShareButton(
                route: 'mymenu/prediction',
                title: "参与预测活动，赢 iPhone 14 Pro",
                content: "还有千元京东卡等你拿",
              )
            ],
            aboveWidget: Stack(
              alignment: Alignment.bottomCenter,
              children: [
                Positioned(
                  right: 0,
                  bottom: 8+(logic.scorllInfo.hasValue == true?(25+16):0),
                  child: const KingRuleItem(title: "活动规则", button: "king_tip")),
                if(logic.scorllInfo.hasValue)
                Positioned(
                  bottom: 16,
                  child: KingScrollBar(info: logic.scorllInfo)),
              ]),
            body: (physics) => LoadingWidget<bool>(
              isLoading: logic.matchList.every((element) => element == null),
              data: logic.dayList?.length == 0,
              child: () => Container(
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [Colours.blueD4E3FF, Colours.white])),
                child: Column(children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: List<Widget>.generate(
                        logic.button.keys.length,
                        (index) => Flexible(
                          child: QkdButton(
                              width: Get.width,
                              height: 40,
                              borderRadius: 8,
                              backgroundColor: Colours.main,
                              text: logic.button.values.toList()[index],
                              textStyle: const TextStyle(
                                  fontSize: 14, color: Colours.white),
                              onPressed: () {
                                Utils.onEvent('ycking_bd',
                                    params: {"ycking_bd": "$index"});
                                User.needLogin(() {
                                  if (logic.button.keys.toList()[index] <= 3) {
                                    Get.toNamed(Routes.kingRank,
                                        arguments: logic.button.keys.toList()[index]);
                                  }
                                  if (logic.button.keys.toList()[index] > 3) {
                                    Get.toNamed(Routes.kingHistory);
                                  }
                                });
                              }),
                        )).insertEvery(Container(width: 8)),
                  ).paddingOnly(top: 16, left: 16, right: 16),
                  Row(children: [
                    QkdText("每日预测(${logic.total}场)",
                      fontSize: 16,
                      fontWeight: FontWeight.w500
                    ),
                    const Spacer(),
                    QkdText("免费次数：${logic.data?.sendCount ?? "0"}次",
                      fontSize: 12, color: Colours.grey66
                    ),
                    Container(width: 4),
                    Image.asset(
                            width: 12,
                            Utils.getImgPath("question_mark_border.png"))
                        .tap(() => Get.dialog(QkdDialog.single("免费次数说明",
                            content: "1.每场比赛会赠送您2次预测机会。\n"
                                "2.赠送次数在最后一场比赛预测截止时失效。\n"
                                "3.比赛取消不退还赠送次数。"))),
                    Container(width: 16),
                    QkdText("赠送次数：${logic.data?.saveCount ?? "0"}次",
                      fontSize: 12, color: Colours.grey66
                    ),
                    Container(width: 4),
                    Image.asset(
                      width: 12,
                      Utils.getImgPath("question_mark_border.png")
                    ).tap(() => Get.dialog(QkdDialog.single("赠送次数说明",
                      content: "1.每充值50元自动兑换1次预测机会。\n"
                        "2.充值兑换次数有效期3个月。\n"
                        "3.比赛取消退还兑换次数。")))
                  ]).paddingOnly(top: 12, left: 16, right: 16),
                  RectDateBar.light(
                      dateList: logic.dayList ?? [],
                      margin: const EdgeInsets.fromLTRB(16, 12, 16, 0),
                      controller: logic.tabController),
                  Expanded(
                      child: TabBarView(
                    controller: logic.tabController,
                    children: List.generate(
                        logic.dayList?.length ?? 0,
                        (index) => LoadingWidget<bool>(
                              isLoading: false,
                              data: logic.matchList[index]?.length == 0,
                              child: () => MediaQuery.removePadding(
                                context: context,
                                removeTop: true,
                                child: ListView(
                                  children: List.generate(
                                      logic.matchList[index]?.length ?? 0,
                                      (i) =>
                                          matchItem(logic.matchList[index]?[i])
                                              .paddingOnly(
                                                  top: i == 0 ? 12 : 0)),
                                ),
                              ),
                            )),
                  ))
                ]),
              ),
            )),
      );
    });
  }

  Widget matchItem(KingEntity? entity) {
    return Block(
      cardStyle: CardStyle(
          margin: const EdgeInsets.fromLTRB(16, 0, 16, 12),
          padding: const EdgeInsets.fromLTRB(16, 10, 16, 12)),
      child: Column(children: [
        DefaultTextStyle(
          style: TextStyle(fontSize: 14, color: Colours.grey66),
          child: Row(children: [
            QkdText(entity?.leagueName ?? ""),
            Container(width: 4),
            QkdText(entity?.matchTime ?? ""),
            const Spacer(),
            QkdText("分析"),
            Container(width: 2),
            Image.asset(width: 12, Utils.getImgPath("arrow_right_36.png"))
          ]).tap(() =>
              Get.toNamed(Routes.zqMatchDetail, arguments: entity?.matchId)),
        ),
        Container(height: 10),
        Container(
            padding: const EdgeInsets.symmetric(vertical: 9),
            decoration: BoxDecoration(
                color: Colours.greyF8, borderRadius: BorderRadius.circular(8)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Column(
                    children: [
                      CachedNetworkImage(
                          width: 52,
                          height: 52,
                          placeholder: (context, url) =>
                              Styles.placeholderIcon(),
                          errorWidget: (
                            context,
                            url,
                            error,
                          ) =>
                              Image.asset(
                                  Utils.getImgPath("zq_placeholder.png")),
                          imageUrl: entity?.homeLogo ?? ""),
                      Container(height: 4),
                      QkdText(entity?.homeName ?? "",
                        textAlign: TextAlign.center,
                        maxLines: 2,
                        fontWeight: FontWeight.w500
                      )
                    ],
                  ),
                ),
                QkdText.style(entity?.guessTime ?? "",
                    style: entity?.guessTime?.contains(":") == true
                        ? const TextStyle(
                            color: Colours.text,
                            fontSize: 22,
                            fontWeight: FontWeight.w500,
                            fontFamily: "Din")
                        : const TextStyle(fontSize: 14, color: Colours.grey66),
                    textAlign: TextAlign.center),
                Expanded(
                  child: Column(
                    children: [
                      CachedNetworkImage(
                          width: 52,
                          height: 52,
                          placeholder: (context, url) =>
                              Styles.placeholderIcon(),
                          errorWidget: (
                            context,
                            url,
                            error,
                          ) =>
                              Image.asset(
                                  Utils.getImgPath("zq_placeholder.png")),
                          imageUrl: entity?.guestLogo ?? ""),
                      Container(height: 4),
                      QkdText(entity?.guestName ?? "",
                        textAlign: TextAlign.center,
                        fontWeight: FontWeight.w500
                      )
                    ],
                  ),
                ),
              ],
            )),
        Container(height: 12),
        QkdButton.large(
            text: entity?.guessStatus ?? "",
            height: 37,
            borderRadius: 8,
            backgroundColor: backColor(entity?.guessStatus),
            textStyle: const TextStyle(fontSize: 14, color: Colours.white),
            onPressed: () async {
              if (entity?.guessStatus != "您未参加本场预测") {
                bool result = await Get.toNamed(Routes.kingDetail,
                    arguments: entity?.matchId);
                if (result) logic.getData(index: logic.tabController.index);
              }
            })
      ]),
    );
  }

  Color backColor(String? status) {
    switch (status) {
      case "选择本场预测结果":
        return Colours.main;
      case "查看我的预测":
        return Colours.redBC4F4F;
      default:
        return Colours.main.withOpacity(0.4);
    }
  }
}
